<?php

class LinkController extends BaseController {

  /**
   * Adds a link.
   * @return type
   */
  public function addLink() {
    $block = Auth::user()->blocks()->find(intval(Input::get('block_id')));

    $link                 = new Link;
    $link->title          = Input::get('name');
    $link->URL            = Input::get('url');
    $link->tempestuser_id = Auth::user()->id;
    $link->block_id       = is_null($block) ? NULL : $block->id;
    // get  order:
    // get order:
    $order                = Auth::user()->links()->where('block_id', '-', Input::get('block_id'))->max('order');
    $max                  = is_null($order) ? 1 : $order + 1;
    $link->order          = $max;

    $validator = Validator::make($link->toArray(), Link::$rules);
    if (!$validator->fails()) {
      $link->save();
      Session::flash('currentPage', $block->page()->first()->id);
      Session::flash('success', 'New link created!');
      return Redirect::to('/');
    }
    Session::flash('error', $validator->messages()->first());
    return Redirect::to('/');
  }

  public function deleteLink() {
    $link = Auth::user()->links()->find(intval(Input::get('id')));
    if ($link) {
      Session::flash('currentPage', $link->block()->first()->page_id);
      $link->delete();
      Session::flash('success', 'Link deleted');
    } else {
      Session::flash('error', 'Could not delete link.');
    }

    return Redirect::to('/');
  }

  public function editLink() {
    $link  = Auth::user()->links()->find(intval(Input::get('id')));
    $block = Auth::user()->blocks()->find(intval(Input::get('block_id')));
    if ($link && $block) {
      $link->title    = Input::get('title');
      $link->block_id = $block->id;
      $link->URL      = Input::get('url');

      $validator = Validator::make($link->toArray(), Link::$rules);
      if (!$validator->fails()) {
        $link->save();
        Session::flash('currentPage', $block->page()->first()->id);
        Session::flash('success', 'Link edited!');
        return Redirect::to('/');
      }
      Session::flash('error', $validator->messages()->first());
      return Redirect::to('/');
    }
    Session::flash('error', 'Could not edit link.');
    return Redirect::to('/');
  }

  public function getInfo() {
    $link = Auth::user()->links()->find(intval(Input::get('id')));
    if ($link) {
      return Response::json($link->toArray());
    }
    return App::abort(404);
  }

  public function sortLink() {
    $link = Auth::user()->links()->find(intval(Input::get('id')));
    if ($link) {
      $link->order = intval(Input::get('order'));
      $validator   = Validator::make($link->toArray(), Page::$rules);
      if (!$validator->fails()) {
        $link->save();
        return Response::json(true);
      }
      return Response::json(false);
    }
  }

}